package com.lucifer.treasure.command;

import com.lucifer.treasure.enchant.effect.SwordAuraEnchantmentEffect;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.context.CommandContext;
import net.minecraft.server.command.CommandManager;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.Text;

/**
 * 御剑术切换命令处理器
 */
public class SwordAuraToggleCommand {
    
    /**
     * 注册命令
     */
    public static void register(CommandDispatcher<ServerCommandSource> dispatcher) {
        dispatcher.register(CommandManager.literal("sword_aura_toggle")
            .executes(SwordAuraToggleCommand::toggleSwordAura));
        
        System.out.println("🔧 [命令] 御剑术切换命令已注册：/sword_aura_toggle");
    }
    
    /**
     * 切换御剑术状态
     */
    private static int toggleSwordAura(CommandContext<ServerCommandSource> context) {
        ServerCommandSource source = context.getSource();
        
        // 确保命令来自玩家
        if (source.getEntity() instanceof ServerPlayerEntity player) {
            try {
                // 获取玩家的御剑术等级
                int auraLevel = SwordAuraEnchantmentEffect.getPlayerSwordAuraLevel(player);
                
                if (auraLevel > 0) {
                    // 切换御剑术状态
                    boolean beforeToggle = SwordAuraEnchantmentEffect.isAuraEnabled(player.getUuid());
                    SwordAuraEnchantmentEffect.toggleAuraFromClient(player);
                    boolean afterToggle = SwordAuraEnchantmentEffect.isAuraEnabled(player.getUuid());
                    
                    System.out.println("🔧 [服务端命令] 玩家 " + player.getName().getString() + " 切换御剑术状态: " 
                                     + (beforeToggle ? "开启" : "关闭") + " → " + (afterToggle ? "开启" : "关闭"));
                    
                    // 发送确认消息给玩家
                    String statusText = afterToggle ? "§a开启" : "§c关闭";
                    player.sendMessage(Text.literal("§b[御剑术]已" + statusText), true);
                    
                    return 1; // 成功
                } else {
                    // 没有御剑术附魔
                    player.sendMessage(Text.literal("§c需要装备有御剑术附魔的武器！"), true);
                    System.out.println("⚠️ [服务端命令] 玩家 " + player.getName().getString() + " 尝试切换御剑术，但没有附魔武器");
                    return 0; // 失败
                }
            } catch (Exception e) {
                System.err.println("❌ [服务端命令] 处理御剑术切换时出错: " + e.getMessage());
                player.sendMessage(Text.literal("§c切换御剑术时出错！"), true);
                return 0; // 失败
            }
        } else {
            // 非玩家执行命令
            source.sendFeedback(() -> Text.literal("§c此命令只能由玩家执行！"), false);
            return 0; // 失败
        }
    }
} 